<template>
  <div class="app-container">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="项目名称" prop="projectName">
          <el-input
            v-model="queryParams.projectName"
            placeholder="请输入项目名称"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="项目类型" prop="projectTypeId">
          <el-select v-model="queryParams.projectTypeId" placeholder="请选择项目类型" clearable>
            <el-option
              v-for="dict in typeAllList"
              :key="dict.id"
              :label="dict.name"
              :value="dict.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间" prop="dateRange">
          <el-date-picker
            v-model="queryParams.dateRange"
            value-format="yyyy-MM-dd"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <TableCard>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['cooperate:projReport:add']"
            >新增
            </el-button>
          </el-col>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

          <el-table :border="Global.tableShowBorder" v-loading="loading" :data="list">
            <el-table-column label="项目名称" align="center" prop="projectName"/>
            <el-table-column label="项目类型名称" align="center" prop="projectTypeName"/>
            <!-- <el-table-column label="汇报内容" align="center" prop="content" show-overflow-tooltip>
              <template slot-scope="{row}">
                <span v-html="row.content"></span>
              </template>
            </el-table-column> -->
            <el-table-column label="创建者用户名" align="center" prop="createByName"></el-table-column>
            <el-table-column label="创建者昵称" align="center" prop="createByNickName" show-overflow-tooltip></el-table-column>
            <el-table-column label="是否点赞" align="center" prop="like">
              <template slot-scope="{row}">
                <dict-tag :options="dict.type.comm_yes_no" :value="row.like"/>
              </template>
            </el-table-column>
            <el-table-column label="创建时间" align="center" prop="createTime"></el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200">
              <template slot-scope="{row}">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  @click="handleUpdate(row)"
                  v-hasPermi="['cooperate:projReport:edit']"
                >修改
                </el-button>
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click="handleDelete(row)"
                  v-hasPermi="['cooperate:projReport:remove']"
                >删除
                </el-button>
                <el-button
                type="text"
                @click="handleDetail(row)"
                v-hasPermi="['cooperate:projReport:query']">查看详情</el-button>
                <el-button
                type="text"
                @click="handledianzan(row)"
                v-hasPermi="[row.like == 1 ? 'cooperate:reportLike:edit' : 'cooperate:reportLike:add']">{{row.like == 1 ? '取消点赞' : '点赞'}}</el-button>
              </template>
            </el-table-column>
          </el-table>

          <pagination
            v-show="total>0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getList"
          />
      </TableCard>
      <!-- 添加或修改对话框 -->
      <el-dialog :title="title" :visible.sync="open" width="80%" append-to-body>
        <el-form ref="form" :model="form" :rules="rules" label-width="120px">
          <el-row class="diy-text-sm diy-leading-10" :gutter="10" v-if="title == '查看详情'">
            <el-col :span="item.span || 12" v-for="(item,index) in formDetail" :key="index">
              <div class="flex_hcneter">
                <svg-icon v-if="item.prop != 'attachmentList'" icon-class="dot" class-name='diy-text-primary diy-mr-1'/>
                <div v-if="item.zidian && item.isCustom" class="flex_hcneter">
                  {{item.label}}：<dict-tag :options="dict.type[item.zidian]" :value="form[item.prop]"/>
                </div>
                <div v-else-if="item.prop == 'content' && item.isCustom">
                  {{item.label}}：
                  <div v-html="form[item.prop]"></div>
                </div>
                <div v-else-if="item.prop == 'avatar' && item.isCustom" class="flex_hcneter">
                  {{item.label}}：
                  <el-image v-if="form[item.prop]"
                    style="width: 100px; height: 100px"
                    :src="form[item.prop]"
                    :preview-src-list="[form[item.prop]]">
                  </el-image>
                </div>
                <div v-else-if="item.prop == 'attList' && item.isCustom">
                  <h2>{{item.label}}</h2>
                  <el-row v-for="(item1,index1) in form[item.prop]" :key="index1">
                    <el-col :span="24">
                      <svg-icon  icon-class="dot" class-name='diy-text-primary diy-mr-1'/>
                      文件名称：{{item1.fileName}}
                    </el-col>
                    <el-col :span="24">
                      <div class="flex_hcneter">
                        <svg-icon  icon-class="dot" class-name='diy-text-primary diy-mr-1'/>
                        文件路径：<el-link type="primary" @click="urlLink(item1.url)">{{item1.url}}</el-link>
                      </div>
                    </el-col>
                  </el-row>

                </div>
                <div v-else-if="item.prop == 'comments' && item.isCustom" class="flex_flex">
                  <div class="flex_hcneter_bet">
                    <h2>{{item.label}}</h2>
                    <el-button
                      type="primary"
                      plain
                      icon="el-icon-plus"
                      size="mini"
                      @click="handleplAdd"
                      v-hasPermi="['cooperate:reportComment:add']"
                    >新增
                    </el-button>
                  </div>
                  <el-table :border="Global.tableShowBorder" :data="form[item.prop]">
                    <el-table-column label="用户名" align="center" prop="userName"/>
                    <el-table-column label="昵称" align="center" prop="nickName"/>
                    <el-table-column label="用户头像" align="center" prop="avatar">
                      <template slot-scope="{row}">
                        <el-image
                          style="width: 100px; height: 100px"
                          :src="row.avatar"
                          :preview-src-list="[row.avatar]">
                        </el-image>
                      </template>
                    </el-table-column>
                    <el-table-column label="评论内容" align="center" prop="content">
                      <template slot-scope="{row}">
                        <span v-html="row.content"></span>
                      </template>
                    </el-table-column>
                    <el-table-column label="创建时间" align="center" prop="createTime"></el-table-column>
                    <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200">
                      <template slot-scope="{row}">
                        <el-button
                          size="mini"
                          type="text"
                          icon="el-icon-edit"
                          @click="handleplUpdate(row)"
                          v-hasPermi="['cooperate:reportComment:edit']"
                        >修改
                        </el-button>
                        <el-button
                          size="mini"
                          type="text"
                          icon="el-icon-delete"
                          @click="handleplDelete(row)"
                          v-hasPermi="['cooperate:reportComment:remove']"
                        >删除
                        </el-button>
                      </template>
                    </el-table-column>
                  </el-table>
                </div>
                <div v-else>{{item.label}}：{{ form[item.prop] }}{{ item.danwei || '' }}</div>
              </div>
            </el-col>
          </el-row>
          <div v-else>
            <el-row>
              <el-col :span="24">
                <el-form-item label="项目" prop="projId">
                  <el-select
                  v-loadMore="ajaxMet"
                  filterable
                  remote reserve-keyword
                  v-model="form.projId"
                  :remote-method="boweiSearch"
                  placeholder="请选择项目"
                  class="diy-w-full" clearable>
                    <el-option
                      v-for="(item,index) in projectList"
                      :key="index"
                      :label="item.name"
                      :value="item.id"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="汇报内容" prop="content">
                  <el-input v-model="form.content" type="textarea" :rows="6" placeholder="请输入汇报内容"/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row v-for="(item,index) in form.attList" :key="index">
              <el-col :span="12">
                <el-form-item label="文件名称"
                :prop="'attList.' + index + '.fileName'"
                :rules="{
                  required: true, message: '文件名称不能为空', trigger: 'blur'
                }">
                  <el-input v-model="item.fileName"  placeholder="请输入文件名称"/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="文件类型"
                :prop="'attList.' + index + '.category'"
                :rules="{
                  required: true, message: '文件类型不能为空', trigger: 'blur'
                }">
                  <el-select v-model="item.category" placeholder="请选择文件类型" clearable>
                    <el-option
                      v-for="dict in dict.type.project_file_type"
                      :key="dict.value"
                      :label="dict.label"
                      :value="Number(dict.value)"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="文件路径"
                :prop="'attList.' + index + '.url'"
                :rules="{
                  required: true, message: '文件路径不能为空', trigger: 'blur'
                }">
                  <div class="flex_hcneter">
                    <FileUpload :limit="1"  v-model="item.url" v-if="item.category == 2"
                    :fileType="['txt','doc','docx','pdf','ppt','pptx','xls','xlsx']" returnData="Array"
                    accept=".txt,.doc,.docx,.pdf,.ppt,.pptx,.xls,.xlsx" fileName="files" :fileData="{'category':item.category}"
                    action="/oa-pcapi/cooperate/projReportAtt/uploadAtt" btnName="选择"></FileUpload>
                    <FileUpload :limit="1"  v-model="item.url" v-else-if="item.category == 3"
                    :fileType="['amr','wav','m4a','flac','aac','mp3','mp4','wma','wmv','mkv','ts']" returnData="Array"
                    accept=".amr,.wav,.m4a,.flac,.aac,.mp3,.mp4,.wma,.wmv,.mkv,.ts" fileName="files" :fileData="{'category':item.category}"
                    action="/oa-pcapi/cooperate/projReportAtt/uploadAtt" btnName="选择"></FileUpload>
                    <imageUpload
                    :fileType="['bmp','jpg','png','gif',]" returnData="Array" fileName="files" :fileData="{'category':item.category}"
                    accept=".bmp,.jpg,.png,.gif," action="/oa-pcapi/cooperate/projReportAtt/uploadAtt"
                    v-model="item.url" :limit="1" v-else></imageUpload>
                    <div style="margin-left:10px;">
                      <el-button type="primary" @click="addlist" icon="el-icon-plus"></el-button>
                      <el-button type="primary" @click="delList(index)" v-if="form.attList.length > 1" icon="el-icon-minus"></el-button>
                    </div>
                  </div>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" v-if="title != '修改记录'" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>

      <!-- 对话框 -->
      <el-dialog :title="plTitle" :visible.sync="plOpen" width="50%" append-to-body>
        <el-form ref="plForm" :model="plForm" :rules="plRules" label-width="120px">
          <el-form-item label="评论内容" prop="content">
            <el-input v-model="plForm.content" type="textarea" :rows="6" placeholder="请输入评论内容"/>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="plSubmitForm">确 定</el-button>
          <el-button @click="plOpen = false">取 消</el-button>
        </div>
      </el-dialog>
  </div>
</template>

<script>
import {listProjReport, getProjReport, addProjReport, updateProjReport, delProjReport} from "@/api/collaWorryFree/projectWorkReport";
import {getReportComment, addReportComment, updateReportComment, delReportComment,like,unlike,} from "@/api/collaWorryFree/comment";
import {listAllProjectType,} from "@/api/collaWorryFree/projectType";
import {listProject,} from "@/api/collaWorryFree/project";
import { math } from "@/utils/math";
export default {
  name: "ProjectWorkReport",
  dicts: ['comm_yes_no','project_file_type',],
  components: {},
  data() {
    return {
      // 遮罩层
      loading: true,
      xgLoading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      xgTotal: 0,
      xmTotal: 0,
      // 表格数据
      list: [],
      // 弹出层标题
      title: "",
      plTitle: "",
      // 是否显示弹出层
      open: false,
      plOpen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        dateRange: [],projectTypeId: null,projectName: null,
      },
      xgQueryParams: {
        pageNum: 1,
        pageSize: 10,dateRange: [],infoName: null,category: null,
      },
      // 表单参数
      form: {},
      plForm: {},
      // 表单校验
      rules: {
        content: [ {required: true, message: "项目名称不能为空", trigger: "blur"} ],
        projId: [ {required: true, message: "汇报内容不能为空", trigger: "change"} ],
      },
      plRules: {
        content: [ {required: true, message: "汇报内容不能为空", trigger: "blur"} ],
      },
      // 查询参数
      xmQueryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      xmZongshu:0,//项目下拉总页数
      projectList:[],//项目数据
      xgRecod:[],//修改记录数据
      typeAllList:[],//所有类型数据
      formDetail:[
        {label:'用户名',prop:'createByName',},{label:'昵称',prop:'createByNickName',},{label:'头像',prop:'avatar',isCustom:true,span:24,},
        {label:'项目名称',prop:'projectName',},{label:'项目类型名称',prop:'projectTypeName',},
        {label:'汇报内容',prop:'content',isCustom:true,span:24,},{label:'是否已读',prop:'read',zidian:'comm_yes_no',isCustom:true,},
        {label:'是否点赞',prop:'like',zidian:'comm_yes_no',isCustom:true,}, {label:'已读数量',prop:'readNum',},
        {label:'点赞数量',prop:'likeNum',}, {label:'评论数量',prop:'commentNum',},{label:'创建时间',prop:'createTime',},
        {label:'附件列表',prop:'attList',isCustom:true,span:24,},{label:'评论列表',prop:'comments',isCustom:true,span:24,},

      ],
    };
  },
  created() {
    this.listAllProjectType()
    this.getList();
  },
  methods: {
    addlist(){//添加列表
      this.form.attList.push({category:1,})
    },
    delList(index){//删除列表
      this.form.attList.splice(index,1)
    },
    boweiSearch(e){//项目下拉输入搜索事件
      this.xmQueryParams.pageNum = 1
      this.projectList = []
      this.xmQueryParams.name = e
      this.listProject(e)
    },
    ajaxMet(){//项目下拉加载事件
      console.log(this.xmZongshu)
      if(this.xmQueryParams.pageNum + 1 > this.xmZongshu) return
      this.xmQueryParams.pageNum = this.xmQueryParams.pageNum + 1
      this.listProject()
    },
    async listProject(){//获取项目数据
      listProject(this.xmQueryParams).then((response) => {
        let rows = response.rows || []
        if(this.xmQueryParams.pageNum == 1) this.projectList = []
        // 找到不在项目列表的数据
        let list = rows.filter(item=>{
            return !this.projectList.some(i=>item.id == i.id)
          })
        //添加进列表中
        this.projectList = this.projectList.concat(list);
        this.xmTotal = response.total
        this.xmZongshu = Math.ceil( math.divide(response.total,this.xmQueryParams.pageSize) )
      });
    },
    async listAllProjectType(){//查询所有项目类型列表
      let res = await listAllProjectType()
      let data = res.data || []
      this.typeAllList = data
    },
    /** 查询列表 */
    getList() {
      this.loading = true;
      let queryParams = {...this.queryParams}
      let dateRange = queryParams.dateRange || []
      if(dateRange.length) {
        queryParams.createStart = dateRange[0]
        queryParams.createEnd = dateRange[1]
      }
      delete queryParams.dateRange
      listProjReport(queryParams).then(response => {
        this.list = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {attList:[{category:1,}],};
      this.resetForm("form");
      this.xmQueryParams.pageNum = 1
      this.projectList = []
      this.listProject()
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length != 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加项目工作汇报";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getProjReport(id).then(response => {
        let data = response.data || {};
        this.form = {
          ...data,
        }
        this.open = true;
        this.title = "修改项目工作汇报";
      });
    },
    handleDetail(row) {//查看详情
      const id = row.id
      this.open = true;
      this.title = "查看详情";
      this.getProjReport(id)
    },
    async getProjReport(id){
      let response = await getProjReport(id)
      let data = response.data || {}
      let comments = data.comments || []
      this.form = {
        ...data,attList:data.attList || [],
        content:this.$changeLine(data.content || ''),
        comments:comments.map(item=>{
          return {...item,content:this.$changeLine(item.content || ''),}
        }),
      }
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          let form = {...this.form}
          let dateRange = form.dateRange || []
          if(dateRange.length) {
            form.startDate = dateRange[0]
            form.endDate = dateRange[1]
          }
          if (this.form.id != undefined) {
            updateProjReport(form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addProjReport(form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    // 表单重置
    plReset() {
      this.plForm = {};
      this.resetForm("plForm");
    },
    /** 新增按钮操作 */
    handleplAdd() {
      this.plReset();
      this.plForm.reportId = this.form.id
      this.plOpen = true;
      this.plTitle = "添加评论";
    },
    handleplUpdate(row) {
      this.plReset();
      const id = row.id
      getReportComment(id).then(response => {
        let data = response.data || {};
        this.plForm = { ...data, }
        this.plOpen = true;
        this.plTitle = "修改评论";
      });
    },
    plSubmitForm: function () {
      this.$refs["plForm"].validate(valid => {
        if (valid) {
          let plForm = {...this.plForm}
          if (this.plForm.id != undefined) {
            updateReportComment(plForm).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.plOpen = false;
              this.getProjReport(this.form.id);
            });
          } else {
            plForm.category = 3
            addReportComment(plForm).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.plOpen = false;
              this.getProjReport(this.form.id);
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleplDelete(row) {
      const id = row.id
      this.$modal.confirm('是否确认删除该数据项？').then(function () {
        return delReportComment(id);
      }).then(() => {
        this.getProjReport(this.form.id);
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    handledianzan(e){//点赞和取消点赞
      let api = e.like == 1 ? unlike : like
      let title = e.like == 1 ? '取消点赞' : '点赞'
      this.$modal.confirm(`是否确认${title}该数据项？`).then(function () {
        return api({category:3,reportId:e.id});
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess(title + "成功");
      }).catch(() => {
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const id = row.id || this.ids
      this.$modal.confirm('是否确认删除该数据项？').then(function () {
          return delProjReport(id);
      }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 搜索按钮操作 */
    xgHandleQuery() {
      this.xgQueryParams.pageNum = 1;
      this.listProjUpdRecDetail();
    },
    /** 重置按钮操作 */
    xgResetQuery() {
      this.resetForm("xgQueryForm");
      this.xgHandleQuery();
    },
  }
};
</script>
